#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#include <GL/glut.h>
#include <GL/gl.h>
#include <GL/glu.h>
#include "ObjLoader.h"
#include <iostream>
#include <fstream>
#include <sstream>

using namespace std;

ObjLoader::ObjLoader(string path)
{
	filePath = path;
	bool open = loadObject();
	if (!open)
		cout << "Couldn't open the file" << endl;
}

ObjLoader::~ObjLoader()
{
}

bool ObjLoader::loadObject()
{
	ifstream objFile;
	objFile.open(filePath);
	
	float x, y, z;
	string type;
	
	while (true)
	{
		objFile >> type;

		if (objFile.eof())
			break;

		if (type.compare("v") == 0)
		{
			vector<float> vertex;
			objFile >> x >> y >> z;
			vertex.push_back(x);
			vertex.push_back(y);
			vertex.push_back(z);
			vertices.push_back(vertex);
			//delete &vertex;
			//free(&vertex);
		}
		else if (type.compare("vn") == 0)
		{
			vector<float> normals;
			objFile >> x >> y >> z;
			normals.push_back(x);
			normals.push_back(y);
			normals.push_back(z);
			v_normals.push_back(normals);
			//delete &normals;
			//free(&normals);
		}
		else if (type.compare("f") == 0)
		{
			string vertex1, vertex2, vertex3;
			vector<int> temp;
			vector<int> temp1;
			vector<vector<int>> temp2;
			
			objFile >> vertex1 >> vertex2 >> vertex3;
			
			temp = splitString(vertex1, '/');
			temp1.push_back(temp[0] - 1);
			temp1.push_back(temp[1] - 1);
			temp1.push_back(temp[2] - 1);
			temp2.push_back(temp1);

			temp = splitString(vertex2, '/');
			temp1[0] = (temp[0] - 1);
			temp1[1] = (temp[1] - 1);
			temp1[2] = (temp[2] - 1);
			temp2.push_back(temp1);

			temp = splitString(vertex3, '/');
			temp1[0] = (temp[0] - 1);
			temp1[1] = (temp[1] - 1);
			temp1[2] = (temp[2] - 1);
			temp2.push_back(temp1);

			faces.push_back(temp2);
			//delete &temp;
			//delete &temp1;
			//delete &temp2;
			//free(&temp); free(&temp1); free(&temp2);
		}
	}
	objFile.close();
	return true;
}

vector<int> ObjLoader::splitString(string &str, char delim)
{
	vector<int> split;
	std::stringstream ss(str);
	std::string item;

	while (std::getline(ss, item, delim)) {
		split.push_back(atoi(item.c_str()));
	}
	return split;
}

void ObjLoader::printData()
{
	cout << "Vertices" << endl;
	for (int i = 0; i < vertices.size(); i++)
	{
		cout << vertices[i][0] << " " << vertices[i][1] << " " << vertices[i][2] << endl;
	}

	cout << "Normals" << endl;
	for (int i = 0; i < v_normals.size(); i++)
	{
		cout << v_normals[i][0] << " " << v_normals[i][1] << " " << v_normals[i][2] << endl;
	}

	cout << "Faces" << endl;
	for (int i = 0; i < faces.size(); i++)
	{
		for (int j = 0; j < 3; j++)
		{
			cout << faces[i][j][0] << " " << faces[i][j][1] << " " << faces[i][j][2] << " ";
		}
		cout << endl;
	}
}

